package pack;

class ElementCycled
{
	int num;
	ElementCycled next;
	ElementCycled prev;
	public ElementCycled(int num)
	{
		this.num = num;
		next = this;
		prev = this;
	}
}

public class CycledList
{
	ElementCycled sentry = null;
	int lenght = 0;
	
	public CycledList()
	{
		sentry = new ElementCycled(0);
		lenght = 0;
	}
	
	private String toStr()
	{
		StringBuffer sb = new StringBuffer();
		ElementCycled current = sentry.next;
		sb.append("[");
		while(current != sentry)
		{
			sb.append(current.num);
			current = current.next;
			if(current != sentry)
				sb.append(",");
		}
		sb.append("]");
		return sb.toString();
	}

	private int lenght()
	{
		return lenght;
	}

	private void addToEnd(int num)
	{
		ElementCycled newElement = new ElementCycled(num);
		sentry.prev.next = newElement;

		newElement.prev = sentry.prev;
		newElement.next = sentry;
		
		sentry.prev = newElement;

		lenght++;
	}

	private void addToBegin(int num)
	{
		ElementCycled newElement = new ElementCycled(num);
		sentry.next.prev = newElement;
		
		newElement.next = sentry.next;
		newElement.prev = sentry;
		
		sentry.next = newElement;

		lenght++;
	}
	
	private ElementCycled search(int num)
	{
		ElementCycled current = sentry.next;
		while(current != sentry)
		{
			if(current.num == num)
				return current;
			
			current = current.next;
		}
		
		return null;
	}
	
	private boolean remove(int num)
	{
		ElementCycled current = sentry.next;
		while(current != sentry)
		{
			if(current.num == num)
			{
				current.next.prev = current.prev;
				current.prev.next = current.next;
				lenght--;
				return true;
			}
			
			current = current.next;
		}
		
		return false;
	}
	
	public static void main(String[] args)
	{
		CycledList list = new CycledList();

		list.addToEnd(-1);
		list.addToBegin(0);
		list.addToEnd(1);
		list.addToEnd(2);
		list.addToBegin(3);
		System.out.println(list.toStr());
		list.remove(3);
		list.remove(-1);
		list.remove(2);
		
//		System.out.println(list.search(-1));
		System.out.println(list.toStr());
	}
}
